package com.authapi.sample.api.controller;

import com.authapi.sample.api.entity.Client;
import com.authapi.sample.api.entity.ClientRole;
import com.authapi.sample.api.entity.User;
import com.authapi.sample.api.entity.UserRole;
import com.authapi.sample.api.model.Request.RoleClient.UpdateRoleClientRequest;
import com.authapi.sample.api.model.Request.RoleUser.UpdateRoleUserRequest;
import com.authapi.sample.api.model.Response.Common.Result;
import com.authapi.sample.api.model.Response.Common.ResultList;
import com.authapi.sample.api.service.impl.ClientRoleServiceImpl;
import com.authapi.sample.api.service.impl.ClientServiceImpl;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Baomidou
 * @since 2024-12-18
 */
@RestController
@RequestMapping("/ClientRole")
public class ClientRoleController {

    @Autowired
    private ClientRoleServiceImpl clientRoleService;

    @Autowired
    private ClientServiceImpl clientService;

    @PostMapping("/UpdateClientRole")
    public Result<ClientRole> UpdateClientRole(@RequestBody UpdateRoleClientRequest request) {
        List<String> Ids = clientRoleService
                .query().eq("role_id",request.roleId).list()
                .stream().map(ClientRole::getId).collect(Collectors.toList());
        clientRoleService.removeByIds(Ids);

        for(int i=0;i<request.clientIds.size();i++){
            UUID uuid = UUID.randomUUID();
            String id = uuid.toString();

            int finalI = i;
            var userRole = new ClientRole(){
                {
                    setId(id);
                    setClientId(request.clientIds.get(finalI));
                    setRoleId(request.roleId);
                }
            };
            clientRoleService.save(userRole);
        }

        return Result.Success(null);
    }

    @GetMapping("/GetClientList")
    public ResultList<List<Client>> GetClientList(String roleId) {
        List<String> clientIds = clientRoleService
                .query().eq("role_id",roleId).list()
                .stream().map(ClientRole::getClientId).collect(Collectors.toList());
        if(clientIds.isEmpty()){
            return ResultList.Success(new ArrayList<Client>());
        }
        List<Client> clientList = new ArrayList<>(clientService
                .query().in("id", clientIds).list());

        return ResultList.Success(clientList);
    }
}
